<?php

namespace App\Services;

use App\Models\UserExtend;

class UserExtendService extends ServiceBase
{
    public function getOrCreate($user_id)
    {
        $extend = UserExtend::where('user_id', $user_id)->first();

        // 使用try方式进行创建，可能存在并发的情况创建失败，则在catch处重新拉取数据返回
        try {
            if (!$extend) {
                $extend = new UserExtend;
                $extend->create_time = time();
                $extend->user_id = $user_id;
                $extend->save();
            }
        } catch (\Throwable $exception) {
            $extend = UserExtend::where('user_id', $user_id)->first();
        }

        return $extend;
    }

    public function extendSave(UserExtend $extend)
    {
        $extend->update_time = time();
        $extend->save();
    }

    public function loginSuccess($user_id, $login_time)
    {
        $extend = $this->getOrCreate($user_id);
        if (!$extend) {
            return;
        }

        $extend->last_login_time = $login_time;
        $this->extendSave($extend);

        return true;
    }

    public function paySuccess($order)
    {
        $extend = $this->getOrCreate($order->user_id);
        if (!$extend) {
            return;
        }

        // 首次充值
        if ($extend->first_pay_time == 0) {
            $extend->first_pay_orderid = $order->id;
            $extend->first_pay_time = $order->create_time;
            $extend->first_pay_amount = $order->amount;
        }

        // 当天累计充值
        $today = date('Y-m-d', time());
        if (date('Y-m-d', $extend->last_pay_time) != $today) {
            $extend->today_pay_amount = 0;
        }
        if (date('Y-m-d', $order->create_time) == $today) {
            $extend->today_pay_amount += $order->amount;
        }

        // last_pay_time 一定要放到 当天累计充值 的逻辑后面
        $extend->last_pay_time = $order->create_time;
        $extend->total_pay_amount += $order->amount;
        $extend->total_pay_num += 1;
        $this->extendSave($extend);

        return true;
    }
}
